package com.lqd.mall.security.utils;

import com.lqd.mall.basis.constant.SecurityConstants;
import com.lqd.mall.basis.constant.TokenConstants;
import com.lqd.mall.basis.utils.ServletUtils;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.basis.utils.text.SecurityContextHolder;
import com.lqd.mall.interaction.system.vo.LoginUserVo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;


/**
 * @author 零起点
 * @create 2022-02-19 22:54
 */
public class SecurityUtils {

    /**
     * 获取用户ID
     */
    public static Long getUserId()
    {
        return SecurityContextHolder.getUserId();
    }

    /**
     * 获取请求token
     */
    public static String getToken()
    {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request)
    {
        // 从header获取token标识
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 裁剪token前缀
     */
    public static String replaceTokenPrefix(String token)
    {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }
        return token;
    }

    public static LoginUserVo getLoginUser() {
        return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUserVo.class);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    public static String getUsername() {
        return SecurityContextHolder.getUserName();
    }
}
